package org.kotboot.cons;

import io.jsonwebtoken.*;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

/**
 *
 *
 * @author jisong.sun
 * @date 18-4-28 上午10:16
 * @param
 * @return
 * @modify-by
 */
public class ConsJwt {
    private String id;
    private String secret;
    private long ttl;
    private long refresh_interval;
    private long refresh_ttl;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public long getTtl() {
        return ttl;
    }

    public void setTtl(long ttl) {
        this.ttl = ttl;
    }

    public long getRefresh_interval() {
        return refresh_interval;
    }

    public void setRefresh_interval(long refresh_interval) {
        this.refresh_interval = refresh_interval;
    }

    public long getRefresh_ttl() {
        return refresh_ttl;
    }

    public void setRefresh_ttl(long refresh_ttl) {
        this.refresh_ttl = refresh_ttl;
    }



    public String getLastestSecret(){
        return getSecret();
    }

    /**
     * 由字符串生成加密KEY
     */
    public SecretKey generalKey(){
        String key = getLastestSecret();
        byte[] codekey = Base64.decodeBase64(key);
        SecretKey keySpec = new SecretKeySpec(codekey, 0, codekey.length, "AES");
        return keySpec;
    }


    public String create(String subject){
        SignatureAlgorithm hS256 = SignatureAlgorithm.HS256;
        Date now = new Date();
        long time = now.getTime();
        SecretKey generalKey = generalKey();
        long expMills = getTtl() + time;
        Date exp = new Date(expMills);
        JwtBuilder builder = Jwts.builder()
                .setId(getId())
                .setIssuedAt(now)
                .setExpiration(exp)
                .setSubject(subject)
                .signWith(hS256,generalKey);
        return builder.compact();
    }

    public Jws<Claims> parse(String jwt){
        SecretKey key = generalKey();
        return Jwts.parser().setSigningKey(key).parseClaimsJws(jwt);
    }
}
